package com.ruoyi.common.core.page;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.ColumnParam;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import org.apache.logging.log4j.util.Strings;

import java.util.ArrayList;
import java.util.List;

/**
 * 表格数据处理
 * 
 * @author ruoyi
 */
public class TableSupport
{
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";


    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain()
    {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
        pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        return pageDomain;
    }

    public static PageDomain buildPageRequest()
    {
        return getPageDomain();
    }


    /**
     * 封装分页对象
     */
    public static <T> Page<T> getPage() {
        Page<T> page = new Page<>();
        page.setCurrent(ServletUtils.getParameterToInt(PAGE_NUM) == null ? 1 : ServletUtils.getParameterToInt(PAGE_NUM));
        page.setSize(ServletUtils.getParameterToInt(PAGE_SIZE) == null ? 10 : ServletUtils.getParameterToInt(PAGE_SIZE));
        if (Strings.isNotBlank(ServletUtils.getParameter(ORDER_BY_COLUMN))) {
            page.addOrder(new OrderItem(StringUtils.toUnderScoreCase(ServletUtils.getParameter(ORDER_BY_COLUMN)), Strings.isBlank(ServletUtils.getParameter(IS_ASC)) || "asc".equals(ServletUtils.getParameter(IS_ASC))));
        }
        return page;
    }


    /**
     * 封装分页对象
     */
    public static List<ColumnParam> getColumnQuery(List<ColumnParam> columnQueryList) {
        List<ColumnParam> queryList = new ArrayList<>();
        if (columnQueryList != null && columnQueryList.size() > 0) {
            for (ColumnParam query : columnQueryList) {
                String columnName = query.getColumnName();
                String dict = query.getDict();
                String queryType = query.getQueryType();
                String queryColumnValue = query.getColumnValue();
                if (StringUtils.isBlank(queryType) || StringUtils.isBlank(columnName)) {
                    continue;
                }
                //字典类型的字段  根据字典类型和字典标签获取字典值
                String columnValue = StringUtils.isBlank(dict) ? queryColumnValue : DictUtils.getDictValueOrDefault(dict, queryColumnValue, queryColumnValue);
                if (!ColumnParam.QUERY_TYPE_EMPTY.equals(queryType) && !ColumnParam.QUERY_TYPE_NOT_EMPTY.equals(queryType)) {
                    if (StringUtils.isBlank(columnValue)) {
                        continue;
                    }
                }
                //防止注入
                if (SqlUtil.isValidBySql(columnName)) {
                    switch (queryType) {
                        case ColumnParam.QUERY_TYPE_EMPTY:
                            if (StringUtils.isBlank(dict)) {
                                queryList.add(new ColumnParam("", ColumnParam.QUERY_TYPE_SQL, String.format("%s is null or %s = ''", columnName, columnName)));
                            }else{
                                List<String> dictValueList = DictUtils.getDictValueList(dict);
                                queryList.add(new ColumnParam("", ColumnParam.QUERY_TYPE_SQL, String.format("%s is null or %s not in (%s) ", columnName, columnName, SqlUtil.sqlOfList(dictValueList))));
                            }
                            break;
                        case ColumnParam.QUERY_TYPE_NOT_EMPTY:
                            if (StringUtils.isBlank(dict)) {
                                queryList.add(new ColumnParam("", ColumnParam.QUERY_TYPE_SQL, String.format("%s is not null and %s != ''", columnName, columnName)));
                            }else{
                                List<String> dictValueList = DictUtils.getDictValueList(dict);
                                if (dictValueList == null || dictValueList.size() == 0) {
                                    queryList.add(new ColumnParam("", ColumnParam.QUERY_TYPE_SQL, String.format("%s is not null and %s != ''", columnName, columnName)));
                                } else {
                                    queryList.add(new ColumnParam("", ColumnParam.QUERY_TYPE_SQL, String.format("%s is not null and %s in (%s) ", columnName, columnName, SqlUtil.sqlOfList(dictValueList))));
                                }

                            }
                            break;
                        default:
                            queryList.add(new ColumnParam(columnName.trim(), queryType, columnValue.trim()));
                    }

                }


            }
        }
        return queryList;
    }

    /**
     * 封装分页对象
     */
    public static <T> QueryWrapper<T> getQueryWrapper(List<ColumnParam> columnQueryList) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if (columnQueryList != null && columnQueryList.size() > 0) {
            for (ColumnParam query : columnQueryList) {

                String columnName = query.getColumnName();
                String queryType = query.getQueryType();
                String queryColumnValue = query.getColumnValue();
                if (StringUtils.isBlank(queryType) || StringUtils.isBlank(columnName)) {
                    continue;
                }
                String dict = query.getDict();
                //字典类型的字段  根据字典类型和字典标签获取字典值
                String columnValue = StringUtils.isBlank(dict) ? queryColumnValue : DictUtils.getDictValueByDict(dict, queryColumnValue);
                if (!ColumnParam.QUERY_TYPE_EMPTY.equals(queryType) && !ColumnParam.QUERY_TYPE_NOT_EMPTY.equals(queryType)) {
                    if (StringUtils.isBlank(columnValue)) {
                        continue;
                    }
                }
                switch (queryType) {
                    case ColumnParam.QUERY_TYPE_EQ:
                        wrapper.eq(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_GTE:
                        wrapper.ge(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_GT:
                        wrapper.gt(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_LTE:
                        wrapper.le(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_LT:
                        wrapper.lt(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_LIKE:
                        wrapper.like(columnName, columnValue);
                        break;
                    case ColumnParam.QUERY_TYPE_NOT_LIKE:
                        wrapper.and(t -> t.notLike(columnName, columnValue).or().isNull(columnName));
                        break;
                    case ColumnParam.QUERY_TYPE_NE:
                        wrapper.and(t -> t.ne(columnName, columnValue).or().isNull(columnName));
                        break;
                    case ColumnParam.QUERY_TYPE_EMPTY:
                        if (StringUtils.isBlank(dict)) {
                            wrapper.and(t -> t.isNull(columnName).or().eq(columnName, ""));
                        } else {
                            List<String> dictValueList = DictUtils.getDictValueList(dict);
                            if (dictValueList == null || dictValueList.size() == 0) {
                                wrapper.and(t -> t.isNull(columnName).or().eq(columnName, ""));
                            }else{
                                wrapper.and(t -> t.isNull(columnName).or().notIn(columnName, dictValueList));
                            }
                        }
                        break;
                    case ColumnParam.QUERY_TYPE_NOT_EMPTY:
                        if (StringUtils.isBlank(dict)) {
                            wrapper.isNotNull(columnName).ne(columnName, "");
                        } else {
                            List<String> dictValueList = DictUtils.getDictValueList(dict);
                            if (dictValueList == null || dictValueList.size() == 0) {
                                wrapper.isNotNull(columnName).ne(columnName, "");
                            } else {
                                wrapper.isNotNull(columnName).in(columnName, dictValueList);
                            }
                        }
                        break;
                    case ColumnParam.QUERY_TYPE_IN:
                        wrapper.in(columnName, Convert.toStrList(columnValue));
                        break;
                    case ColumnParam.QUERY_TYPE_NOT_IN:
                        wrapper.and(t -> t.notIn(columnName, Convert.toStrList(columnValue)).or().isNull(columnName));
                        break;
                }
            }
        }
        return wrapper;
    }
}
